<?php

/**
*搜索控制器
*视频、赛事搜索
*@author susy<susy.liang@ilongyuan.com.cn>
*/

namespace Home\Controller;

class SearchController extends HomeController {

   
	/**
    *基础参数的初始化
    */
    protected function _initialize(){

    	parent::_initialize();

        
    }

    /**
    *默认关键字搜索
    */
    public function index(){
        C('DEFAULT_THEME', 'v4');
        setRedirect();

        $this->keywords = I('keywords', '', 'trim');
        $this->display();
    }

    /**
    *视频标签搜索
    */
    public function tag(){

        $tag = I('keyword', '');
        if(empty($tag))
            $this->error('请选择标签');

        $service = D('Common/Video', 'Service');
        $pager     = I('pager', C('HOME_VIDEO_PER',NULL, 5), 'intval');
        $timestamp    = I('timestamp',0, 'intval');

        $map = array();
        $map['tags']   =  $tag;
        $map['status'] = $service::STATUS_PASS;
        $map['race_id'] = array('egt', null);
        $map['create_time'] = $timestamp ? array('lt', $timestamp) : array('$gt' => 0);

        $ids   = $service->where($map)->order('create_time desc')->limit($pager)->getField('id', true);
        if($ids)
            $lists = $this->lists_format($ids);

        if($lists){
            $count = count($lists);
            $this->timestamp = $lists[$count-1]['timestamp'];
            $this->data  = $lists ? $lists : array();
        }

        $this->topicTitle = $tag;

        if(IS_AJAX){
            $strhtml = $this->fetch('Template:video');
            $result = array('state'=>0, 'info'=>'操作成功',
                  'data'=>array('content'=>$strhtml, 'total'=>count($lists), 'limit'=>$pager));
            $this->ajaxReturn($result);
        }else{
            $this->display('index');
        }
       
    }

    public function video() {
        C('DEFAULT_THEME', 'ui3');
        setRedirect();

        $this->keywords = I('keywords', '', 'trim');

        //keywords为空时，加载编辑选推数据
        if (empty($this->keywords)) {
            $topicId = 3;// 编辑选推
            $timestamp = I('timestamp', 0, 'intval');
            $pager = I('pager', 20, 'intval');
            $videos = event('Video')->getByTopicAndGame($topicId, [], $timestamp, $pager);

            $filterMap = array('id','title','thumb','pre_uri','uri', 'dpi_levels', 'detail','user','statis','action','create_time','game_id','game','type','icons', 'tags', 'type', 'status');
            $this->videos = $this->lists_format($videos, $filterMap);

            if (IS_AJAX) {
                $this->ajaxReturn(['state'=>0, 'info'=>'操作成功', 'data' => $this->videos]);
            }
        }
        
        $this->resultPager = 20;
        //header tab
        $this->assign('currentTab', 'find');
        $this->assign('title', '搜索视频');
        $this->display();
    }

    public function user() {
        C('DEFAULT_THEME', 'v4');
        setRedirect();

        $this->keywords = I('keywords', '', 'trim');
        $this->display();
        return;

        C('DEFAULT_THEME', 'ui3');
        setRedirect();

        $this->resultPager = 20;
        $this->keywords = I('keywords', '', 'trim');
        if (empty($this->keywords)) {
            $this->users = $this->activeUser(0, $this->resultPager);
        } else {
            $this->users = [];
        }
        //header tab
        $this->assign('currentTab', 'find');
        $this->assign('title', '搜索用户');
        $this->display();
    }

    /**
     * 根据最后登录时间
     * 查询当前活跃用户
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function activeUser($timestamp = 0, $per = 20) {
        $userService = service('users');
        $map = [];
        if (UID) {
            $map['uid'] = ['ne', UID];
            $map['status'] = 1;
        }
        if ($timestamp) {
            $map['last_login_time'] = ['lt', $timestamp];
        }
        $res = $userService->where($map)->order('last_login_time desc')->limit($per)->field('id,last_login_time')->select();

        $users = [];
        if ($res)
        {
            $userEvent = event('User');
            $followEvent = event('Follow');
            foreach ($res as $value) {
                if (!$value || !$value['id']) continue;
                $user = $userEvent->info($value['id']);
                // uri_format($user['avatar']);
                // uri_format($user['background']);
                $user['follows'] or $user['follows'] = $followEvent->count_follows($user['id']);
                UID && $user['is_follow'] = $followEvent->is_follow(UID, $user['id']) ? 1 : 0;
                $users[] = $user;
                $this->timestamp = $value['last_login_time'];
            }
        }

        if (IS_AJAX) {
            $this->ajaxReturn(['state'=>0, 'info'=>'操作成功', 'data' => $users, 'timestamp' => $this->timestamp]);
        }
        return $users;
    }

    public function explore() {
        $this->searchTag = I('tag', '');
        $this->resultPager = I('pager', 20, 'intval');

        if (empty($this->searchTag)) {
            $sort = I('order', 'create_time');
            $timestamp = I('timestamp', 0, 'intval');
            $p = I('page_no', 1, 'intval');
            $videos = [];
            switch ($sort) {
                case 'create_time':
                    $videos = event('video')->getNew($this->resultPager, $timestamp);
                    break;
                case 'play':
                    $videos = event('video')->getHot($this->resultPager, $p);
                    break;
            }
            $filterMap = array('id','title','thumb','pre_uri','uri', 'dpi_levels', 'detail','user','statis','action','create_time','game_id','game','type','icons', 'tags', 'type', 'status', 'dpi_height', 'dpi_width');
            $this->videos = $this->lists_format($videos, $filterMap);

            if (IS_AJAX) {
                $this->ajaxReturn(['state'=>0, 'info'=>'操作成功', 'data' => $this->videos]);
            }
        }

        C('DEFAULT_THEME', 'ui3');
        setRedirect();

        $this->tags = event('tag')->getHot(10);
        //header tab
        $this->assign('currentTab', 'find');
        $this->assign('title', '探索');
        $this->display();
    }

    public function ajaxVideos()
    {
        $limit = I('limit', 12, 'intval');
        $p = I('p', 1, 'intval');

        $sort = I('order');
        $sort = ($sort == 'hot') ? 'play' : 'create_time';

        $service = D('Video', 'Service');

        $title = I('title', '', 'htmlspecialchars');
        if ($title) {
            event('Cache')->setSearchKey($title);
            $query[]['full_title'] = new \MongoRegex("/".$title."/i");
            $query[]['title'] = new \MongoRegex("/".$title."/i");
            $query[]['tags'] = $title;
            $map['$and'][]['$or'] = $query;
        }
        $map['$and'][]['status'] = $service::STATUS_PASS;
        $map['$and'][]['type']   = $service::TYPE_NORMAL;

        $where['_array'] = $map;
        $total = $service->where($where)->count();
        $videos = event('Video')->getBaseInfoLists($where, true, '', $p, $limit, "$sort desc");
        $this->ajaxReturn(['state' => 0, 'data' => $videos, 'total' => intval($total), 'info' => '']);
    }

    public function ajaxUsers()
    {
        $limit = I('limit', 12, 'intval');
        $p = I('p', 1, 'intval');

        $nickname = I('nickname', '', 'htmlspecialchars');
        if ($nickname) {
            event('Cache')->setSearchKey($nickname);
            $map = [
                'status'   => 1,
                'nickname' => new \MongoRegex("/".$nickname."/i")
            ];
            $total = service('Users')->where($map)->count();
            $users = service('Users')->where($map)
                     ->page($p)->limit($limit)
                     ->order('follows desc, last_login_time desc')
                     ->field('id,nickname,avatar,background,gender,auth_icon')
                     ->select();
        } else {
            if (UID) {
                $map['uid'] = ['ne', UID];
            }
            $map['status'] = 1;
            $total = service('Users')->where($map)->count();
            $users = service('Users')->where($map)
                     ->page($p)->limit($limit)
                     ->order('follows desc, last_login_time desc')
                     ->field('id,nickname,avatar,background,gender,auth_icon')
                     ->select();
        }
        if (empty($users)) {
            $this->ajaxReturn(['state' => 0, 'data' => [], 'info' => '']);
        }

        $TAuthIcon = [];
        foreach ($users as &$user) {
            uri_format($user['avatar']);
            uri_format($user['background']);
            $user['statis']['follows'] = intval(event('Follow')->count_follows($user['id']));
            $user['statis']['videos']  = intval(event('Video')->total(['uid' => $user['id']]));
            $user['action']['is_follow'] = UID ? (event('Follow')->is_follow(UID, $user['id']) ? 1 : 0) : 0;
            if (!empty($user['auth_icon'])){
                if (empty($TAuthIcon[$user['auth_icon']])) {
                    $icon = event('IconPacks')->getIconById($user['auth_icon']);
                    $icon && $TAuthIcon[$user['auth_icon']] = field_filter($icon, ['pic', 'name'], false);
                }
                $auth = $TAuthIcon[$user['auth_icon']];
                $auth && $user['auth'] = $auth;
            }
            unset($user['auth_icon']);
        }
        $users = array_values($users);
        $this->ajaxReturn(['state' => 0, 'data' => $users, 'total' => intval($total), 'info' => '']);
    }
}